#PYTHON3阿里云腾讯云宝塔VUE一键打包FTP上传工具
import ftplib
import os
 
from ftplib import FTP            #加载ftp模块

import subprocess
#等待执行VUE代码打包操作完成
cmd='cnpm run build'
p=subprocess.Popen(cmd,shell=True)
return_code=p.wait()

ftp=FTP()                         #设置变量
ftp.set_debuglevel(2)             #打开调试级别2，显示详细信息
ftp.connect("127.0.0.1",21)          #连接的ftp sever和端口
ftp.login("vue","888H")      #连接的用户名，密码
#print(ftp.getwelcome())

dir="dist"#本地路径
remote_dir="/dist"#服务器上传路径

ftp.set_pasv(True) # 如果被动模式由于某种原因失败，使用主动模式。不然会报错“由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败”
bufsize = 1024



def delAllfile(ftp,ftppath):
    try:
        print (ftppath)
        try:
            ftp.cwd(ftppath)
        except Exception as e:
            print ("进入ftp目录失败" + str(e))
        
        
        dir_res=[]
        ftp.dir('.', dir_res.append)  # 对当前目录进行dir()，将结果放入列表
        print(dir_res)
        # exit()
        for i in dir_res:
            if i.startswith("d"):
                # print(i)
                
                dirName=i.split(" ")[-1]
                print("开始删除"+dirName+"文件夹")
                # exit()
                delAllfile(ftp,ftp.pwd() + "/" + dirName)
                ftp.cwd('..')
                print(ftppath+"/"+dirName)
                ftp.rmd(ftppath + '/' + dirName)
            else:
                # print(i)
                # exit()
                f=i.split(" ")[-1]
                
                # filelist = ftp.getfiles(ftppath)
                # for f in filelist:
                print ("删除FTP目录："+ftppath+"下存在文件:"+f)
                ftp.delete(f)
    except Exception as e:
        raise e
        
delAllfile(ftp,remote_dir)
# exit()

#print(os.walk(dir))
for parent, dirnames, filenames in os.walk(dir):
    for filename in filenames:
        #print(parent)#dist/js
        #print(dirnames)#[]
        #替换windows下的路径分隔符成linux下的路径分隔符
        path=remote_dir+parent.replace(dir,"").replace("\\","/")
        print(path)
        #exit
        #continue
        remotepath = path+"/"+filename
        localpath = os.path.join(parent, filename)
        #print(localpath)
        fp = open(localpath, 'rb')

        #如果远程服务器不存在当前文件夹路径时，需要先创建文件夹路径，然后再上传文件
        try:
            ftp.cwd(path)
        except ftplib.error_perm:
            try:
                ftp.mkd(path)
            except ftplib.error_perm:
                print(path+"文件夹无法创建")
        try:
            ftp.storbinary('STOR ' + remotepath, fp, bufsize)
        except ftplib.error_perm:
            print(remotepath+"文件上传错误")
ftp.set_debuglevel(0)
fp.close()
ftp.quit()